package com.atguigu.boot.converter;

import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zp
 * @version 1.0
 * @description: 自定义异常消息处理器 （如果需要测试自定义异常处理器 需要注释前面俩个自定义异常处理的方法）
 * 或者实现Ordered接口 实现getOrder方法 值为-1
 * @date 2022/9/19 19:26
 */
@Component
public class MyHandlerExceptionResolver implements HandlerExceptionResolver, Ordered {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        printWrite(this.getClass().getSimpleName()+":"+ex.getMessage(),response);
        return new ModelAndView();
    }

    private void printWrite(String msg,HttpServletResponse response){
        try {
            PrintWriter printWriter = response.getWriter();
            printWriter.write(msg);
            printWriter.flush();
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
